<template>
  <div>
    <leftRightSplit :left-span="6">
      <template #left>
        <ContentWrap title="单位部门">
          <unitDeptTree ref="deptTree" @load="chioseDept" @change="chioseDept" />
        </ContentWrap>
      </template>
      <template #right>
        <ContentWrap :title="title">
          <div class="app-container">
            <Search
              ref="search"
              :schema="searchScheme"
              :model="queryParam"
              :is-col="false"
              layout="inline"
              :showSearch="true"
              button-position="left"
              :search-loading="loading"
              :reset-loading="loading"
              @search="handleSearch"
              @reset="handleSearch"
            />
          </div>
          <Table
            :data="users"
            :columns="columns"
            :loading="loading"
            row-key="EmpId"
            :pagination="paging"
            @change="loadUser"
          >
            <template #empBase="e">
              <div class="userInfo">
                <div class="head">
                  <img
                    v-if="e.row.UserHead == null || e.row.UserHead == ''"
                    src="@/assets/imgs/avatar.png"
                    width="50"
                    height="50"
                  />
                  <el-avatar
                    v-else
                    shape="square"
                    :size="50"
                    :src="$formatFileUri(e.row.UserHead)"
                  />
                </div>
                <div class="content">
                  <div class="item">
                    <Icon v-if="e.row.Sex == 1" style="color: #409eff" icon="ep:male" />
                    <Icon v-else-if="e.row.Sex == 2" style="color: #f56c6c" icon="ep:female" />
                    <el-link @click="showEmp(e.row)">{{ e.row.EmpName }}</el-link>
                  </div>
                  <div class="empNo">{{ e.row.EmpNo }}</div>
                </div>
              </div>
            </template>
            <template #IsAdmin="e">
              <el-tag v-if="e.row.IsAdmin" type="success">是管理员</el-tag>
              <el-tag type="warning" v-else>不是管理员</el-tag>
            </template>
            <template #Role="e">
              <el-space>
                <el-link style="margin-right: 10px" :icon="editIcon" @click="editRole(e.row)" />
                <span v-if="e.row.Role == null || e.row.Role.length == 0" style="color: #f56c6c"
                  >未设定角色</span
                >
                <template v-else>
                  <span v-for="i in e.row.Role" :key="i">{{ i }}</span>
                </template>
              </el-space>
            </template>
            <template #Dept="e">
              <span v-if="e.row.IsAdmin" style="color: #409eff">拥有所有部门权限</span>
              <div v-else>
                <BaseButton type="text" :icon="editIcon" @click="editDept(e.row)">
                  <template v-if="e.row.DeptNum !== 0">拥有{{ e.row.DeptNum }}个部门权限</template>
                  <span v-else style="color: #f56c6c">未设定部门权限</span>
                </BaseButton>
              </div>
            </template>
            <template #action="e">
              <BaseButton
                size="small"
                type="warning"
                title="重置登陆密码"
                :icon="refreshIcon"
                circle
                @click="resetPwd(e.row)"
              />
              <BaseButton
                size="small"
                type="danger"
                title="删除用户"
                :icon="dropIcon"
                circle
                @click="dropUser(e.row)"
              />
            </template>
          </Table>
        </ContentWrap>
      </template>
    </leftRightSplit>
    <empRoleSet
      v-model:visible="visible"
      :emp-id="empId"
      :title="roleTitle"
      @close="closeRoleSet"
    />
    <empDeptPower
      v-model:visible="visibleDept"
      :emp-id="empId"
      :title="roleTitle"
      @close="closeDeptSet"
    />
  </div>
</template>

<script>
import * as userApi from '@/api/emp/loginUser'
import { unitDeptTree } from '@/components/unit'
import { Table } from '@/components/Table'
import { Search } from '@/components/Search'
import { useIcon } from '@/hooks/web/useIcon'
import { useUserStoreWithOut } from '@/store/modules/user'
import empDeptPower from './components/empDeptPower.vue'
import empRoleSet from './components/empRoleSet.vue'
const userStore = useUserStoreWithOut()
export default {
  name: 'UserList',
  components: {
    unitDeptTree,
    Search,
    empRoleSet,
    empDeptPower,
    Table
  },
  data() {
    const editIcon = useIcon({ icon: 'ep:edit' })
    const refreshIcon = useIcon({ icon: 'ep:refresh' })
    const dropIcon = useIcon({ icon: 'ep:delete' })
    return {
      editIcon,
      refreshIcon,
      dropIcon,
      users: [],
      title: '用户列表',
      visible: false,
      empId: null,
      roleTitle: null,
      visibleDept: false,
      loading: false,
      searchScheme: [
        {
          field: 'QueryKey',
          label: '关键字',
          component: 'Input',
          componentProps: {
            maxLength: 50,
            placeholder: '人员名/编号/手机号'
          }
        },
        {
          field: 'RoleId',
          label: '拥有的角色',
          component: 'RoleSelect',
          componentProps: {
            multiple: true,
            placeholder: '拥有的角色'
          }
        }
      ],
      columns: [
        {
          field: 'EmpNo',
          label: '人员信息',
          align: 'left',
          width: 250,
          fixed: 'left',
          slotName: 'empBase',
          sortable: 'custom'
        },
        {
          field: 'Phone',
          label: '手机号',
          align: 'center',
          minWidth: 120
        },
        {
          field: 'Email',
          label: 'Email',
          align: 'center',
          minWidth: 120
        },
        {
          field: 'LoginName',
          label: '登陆名',
          align: 'center',
          minWidth: 120
        },
        {
          field: 'IsAdmin',
          label: '是否是管理员',
          align: 'center',
          slotName: 'IsAdmin',
          minWidth: 100
        },
        {
          field: 'Role',
          label: '拥有的角色',
          align: 'left',
          slotName: 'Role',
          minWidth: 200
        },
        {
          field: 'Dept',
          label: '部门权限',
          align: 'left',
          slotName: 'Dept',
          minWidth: 200
        },
        {
          field: 'Action',
          label: '操作',
          align: 'left',
          fixed: 'right',
          width: '100px',
          slotName: 'action'
        }
      ],
      paging: {
        pageSize: 10,
        total: 0,
        currentPage: 1
      },
      queryParam: {
        CompanyId: null,
        QueryKey: null,
        DeptId: null,
        UnitId: null,
        RoleId: null
      }
    }
  },
  computed: {
    comId() {
      return userStore.comId
    }
  },
  mounted() {
    const query = this.$route.query
    this.queryParam.CompanyId = this.comId
    if (query != null) {
      this.initQuery(query)
    }
  },
  methods: {
    showEmp(row) {
      this.$router.push({ name: 'showEmp', params: { id: row.EmpId } })
    },
    handleSearch(data) {
      this.queryParam = Object.assign(this.queryParam, data)
      this.loadUser()
    },
    initQuery(query) {
      if (query.roleId) {
        this.queryParam.RoleId = [query.roleId]
        this.loadUser()
      }
    },
    closeRoleSet(isRefresh) {
      this.visible = false
      if (isRefresh) {
        this.loadUser()
      }
    },
    resetPwd(emp) {
      const title = '确认重置人员 ' + emp.EmpName + '的密码?'
      this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.resetConfirm(emp.EmpId)
      })
    },
    async resetConfirm(empId) {
      await userApi.resetPwd(empId)
      this.$message({
        type: 'success',
        message: '重置成功!'
      })
    },
    closeDeptSet(isRefresh) {
      this.visibleDept = false
      if (isRefresh) {
        this.loadUser()
      }
    },
    editRole(row) {
      this.empId = row.EmpId
      this.roleTitle = '编辑人员' + row.EmpName + '拥有的角色'
      this.visible = true
    },
    editDept(row) {
      this.empId = row.EmpId
      this.roleTitle = '编辑人员' + row.EmpName + '拥有的部门数据权限'
      this.visibleDept = true
    },
    formatStr(rows, def) {
      if (rows == null || rows.length == 0) {
        return h('span', {}, def)
      }
      const str = []
      rows.forEach((c) => {
        str.push(h('span', {}, c))
      })
      return str
    },
    async loadUser(curPaging) {
      if (this.queryParam.CompanyId == null) {
        return
      }
      if (curPaging == null) {
        curPaging = {
          Size: this.paging.pageSize,
          Index: 1,
          SortName: 'EmpId',
          IsDesc: true
        }
        this.paging.currentPage = 1
      }
      const res = await userApi.query(this.queryParam, curPaging)
      if (res.List) {
        this.users = res.List
      } else {
        this.users = []
      }
      this.paging.total = res.Count
    },
    dropUser(emp) {
      const title = '确认删除人员 ' + emp.EmpName + '的用户信息?'
      this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submitDrop(emp.EmpId)
      })
    },
    async submitDrop(id) {
      await userApi.deleteUser(id)
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
      this.loadUser()
    },
    chioseDept(vals, e) {
      this.queryParam.CompanyId = e.companyId
      if (e.value.length === 0) {
        this.queryParam.UnitId = null
        this.queryParam.DeptId = null
        this.title = e.comName[e.companyId] + '公司-人员列表'
      } else {
        const dept = e.value[0]
        if (dept.type === 'unit') {
          this.title = dept.Name + '单位-人员列表'
          this.queryParam.UnitId = [dept.Id]
          this.queryParam.DeptId = null
        } else {
          this.title = dept.Name + '部门-人员列表'
          this.queryParam.UnitId = null
          this.queryParam.DeptId = [dept.Id]
        }
      }
      this.loadUser()
    }
  }
}
</script>
